package com.springboot.framework.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.springboot.framework.exception.BaseException;
import com.springboot.user.entity.User;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * token工具类
 */
public class JWTUtil {

    //过期时间
    private static final long EXPIRE_TIME = 15 * 60 * 1000;
    //私钥
    private static final String TOKEN_SECRET = "privateKey";
    //用户标识的key
    private static final String USER_ID = "openId";

    /**
     * 根据用户参数生成token,将用户的唯一标识保存在 token
     * @return
     */
    public static String getToken(String userOnlyMark){

        try {
            // 设置过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            // 私钥和加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            // 设置头部信息
            Map<String, Object> header = new HashMap<>(2);
            header.put("Type", "Jwt");
            header.put("alg", "HS256");
            // 返回token字符串
            return JWT.create()
                    .withHeader(header)
                    .withClaim(USER_ID, userOnlyMark)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 校验token获取用户保存在token中的数据
     * @param token
     * @return
     */
    public static String decryptToken(String token){
        Algorithm algorithm = null;
        JWTVerifier verifier = null;
        DecodedJWT jwt = null;
        String userId = "";
        try {
            algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            verifier = JWT.require(algorithm).build();
            jwt = verifier.verify(token);
            userId = jwt.getClaim(USER_ID).asString();
            return userId;
        } catch (Exception e){
            throw new BaseException("token检验失败");
        }
    }
}
